let {
    User,
    Message,
    Comment
} = require('../models');
let auth = require('../utils/auth');

let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let userIds = [];

    let msgs = JSON.parse(JSON.stringify(await Message.findAll({
        order: [
            ['id', 'desc']
        ],
        offset: 0,
        limit: 5

    })));


    let msgIds = [];

    msgs.forEach(item => {
        msgIds.push(item.id);
        userIds.push(item.fromUserId);
    });



    let comments = JSON.parse(JSON.stringify(await Comment.findAll({
        where: {
            msgId: msgIds
        }
    })));

    comments.forEach(item => {
        userIds.push(item.fromUserId);
    });

    let userAll = await User.findAll({
        where: {
            id: userIds
        }
    });


    comments.forEach(item => {
        let userInfo = userAll.filter(row => {
            return item.fromUserId === row.id;
        })[0];
        item.comUserName = userInfo === undefined ? '匿名' : userInfo.username;
    })


    msgs.forEach(msg => {
        let sayComments = comments.filter(item => {
            return item.msgId === msg.id;
        });
        let userInfo = userAll.filter(row => {
            return msg.fromUserId === row.id;
        })[0];
        msg.msgUserName = userInfo === undefined ? '匿名' : userInfo.username;
        msg.comments = sayComments;
    })


    let obj = {
        username,
        msgs
    };
    ctx.render('index.html', obj);
};





let fy_fn =async (ctx, next) => {
    let {n} =ctx.request.query

    console.log(n);

    let username = ctx.session.userName;
    let userIds = [];

    let msgs = JSON.parse(JSON.stringify(await Message.findAll({
        order: [
            ['id', 'desc']
        ],
        offset: (n-1)*5,
        limit: 5

    })));


    let msgIds = [];

    msgs.forEach(item => {
        msgIds.push(item.id);
        userIds.push(item.fromUserId);
    });



    let comments = JSON.parse(JSON.stringify(await Comment.findAll({
        where: {
            msgId: msgIds
        }
    })));

    comments.forEach(item => {
        userIds.push(item.fromUserId);
    });

    let userAll = await User.findAll({
        where: {
            id: userIds
        }
    });


    comments.forEach(item => {
        let userInfo = userAll.filter(row => {
            return item.fromUserId === row.id;
        })[0];
        item.comUserName = userInfo === undefined ? '匿名' : userInfo.username;
    })


    msgs.forEach(msg => {
        let sayComments = comments.filter(item => {
            return item.msgId === msg.id;
        });
        let userInfo = userAll.filter(row => {
            return msg.fromUserId === row.id;
        })[0];
        msg.msgUserName = userInfo === undefined ? '匿名' : userInfo.username;
        msg.comments = sayComments;
    })


    let obj = {
        username,
        msgs
    };
    ctx.render('fyss.html', obj);
};




let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};

let register_fn = async (ctx, next) => {
    ctx.render('register.html', {
        msg: ''
    });
};

let loginDone_fn = async (ctx, next) => {

    let uid = ctx.request.body.username || '';
    let pwd = ctx.request.body.password || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = {
                code: 200,
                msg: '登录成功'
            };
        } else {
            res = {
                code: 1000,
                msg: '用户名或密码错误，请确认后重试'
            };
        }

    } else {
        res = {
            code: 1000,
            msg: '用户名和密码不能为空'
        };
    }
    ctx.body = JSON.stringify(res);
};









let registerDone_fn = async (ctx, next) => {

    let uid = ctx.request.body.username || '';
    let pwd = ctx.request.body.password || '';
    let confirmpwd = ctx.request.body.confirmpassword || '';

    let res = '';


    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await User.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json === 'null') {
            let u1 = await User.create({
                username: uid,
                password: pwd
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = {
                    code: 200,
                    msg: '用户注册成功'
                };
            } else {
                res = {
                    code: 1000,
                    msg: '因为服务器或者网络原因，用户未注册成功'
                };
            }
        } else {
            res = {
                code: 1000,
                msg: '当前用户名已经注册，请确认后重试'
            };
        }
    } else {
        res = {
            code: 400,
            msg: '用户名和密码不能为空，且两密码应该一致'
        };
    }

    ctx.body = JSON.stringify(res);
};






let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = {
        code: 200,
        msg: '注销成功'
    };
}





let say_fn = async (ctx, next) => {
    let sayMsg = ctx.request.body.sayMsg || '';
    let userId = ctx.session.userId;
    let say = await Message.create({
        fromUserId: userId,
        content: sayMsg
    });

    let data = JSON.stringify(say);

    ctx.body = {
        code: 200,
        data,
        msg: '发表说说成功'
    };
}







let comment_fn = async (ctx, next) => {
    let commentMsg = ctx.request.body.commentMsg || '';
    let msgId = ctx.request.body.msgId || '';
    let fromUserId = ctx.session.userId;


    let comment = await Comment.create({
        fromUserId: fromUserId,
        msgId: msgId,
        content: commentMsg
    });


    let msg = await Message.findOne({
        where: {
            id: msgId
        }
    });

    let toUserId = msg === undefined ? '0' : msg.fromUserId;


    let users = await User.findAll({
        where: {
            id: [fromUserId, toUserId]
        }
    });


    var fromUserInfo = JSON.parse(JSON.stringify(users.filter(user => {
        return user.id === fromUserId;
    })[0]));


    var toUserInfo = JSON.parse(JSON.stringify(users.filter(user => {
        return user.id === toUserId;
    })[0]));


    let data = JSON.parse(JSON.stringify(comment));


    data.fromUserName = fromUserInfo.username;
    data.toUserName = toUserInfo.username;

    ctx.body = {
        code: 200,
        data,
        msg: '吐槽成功'
    };
}











module.exports = {
    '/': ['get', auth, index_fn],
    '/login': ['get', auth, login_fn],
    '/logout': ['post', auth, logout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/say': ['post', say_fn],
    '/comment': ['post', comment_fn],
    '/home/fy/num':['get',fy_fn]
}